package com.example.rdcproject.ving.notes.view.Admin;

import com.example.rdcproject.ving.notes.entity.Announcement;
import com.example.rdcproject.ving.notes.service.ConnectionPool;
import com.example.rdcproject.ving.notes.util.DBUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AnnouncementBoardView {

    private ConnectionPool connectionPool = ConnectionPool.getInstance();
    private Connection connection = null;
    private Statement statement = null;



    private JFrame frame;
    private JTable noticeTable;
    private JTextField titleField;
    private JTextArea contentArea;
    private JTextField searchField;

    private List<Announcement> noticeList;

    public AnnouncementBoardView() {


        initialize();
        initDatabase();
        loadNoticeData();
        frame.setVisible(true);
    }

    private void initialize() {
        frame = new JFrame("公告栏系统");
        frame.setBounds(100, 100, 800, 500);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel titleLabel = new JLabel("标题：");
        titleLabel.setBounds(20, 20, 60, 20);
        frame.getContentPane().add(titleLabel);

        titleField = new JTextField();
        titleField.setBounds(90, 20, 200, 20);
        frame.getContentPane().add(titleField);

        JLabel contentLabel = new JLabel("内容：");
        contentLabel.setBounds(20, 60, 60, 20);
        frame.getContentPane().add(contentLabel);

        contentArea = new JTextArea();
        contentArea.setBounds(90, 60, 600, 200);
        frame.getContentPane().add(contentArea);


        JButton addButton = new JButton("添加");
        addButton.setBounds(20, 280, 80, 30);
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addNotice();
            }
        });
        frame.getContentPane().add(addButton);

        JButton deleteButton = new JButton("删除");
        deleteButton.setBounds(120, 280, 80, 30);
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteNotice();
            }
        });
        frame.getContentPane().add(deleteButton);

        JButton updateButton = new JButton("修改");
        updateButton.setBounds(220, 280, 80, 30);
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateNotice();
            }
        });
        frame.getContentPane().add(updateButton);

        JButton searchButton = new JButton("查询");
        searchButton.setBounds(320, 280, 80, 30);

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchNotice();
            }
        });
        frame.getContentPane().add(searchButton);


        DefaultTableModel noticeTableModel = new DefaultTableModel(new Object[][]{}, new String[]{"ID", "标题", "内容", "时间"});
        noticeTable = new JTable(noticeTableModel);
        JScrollPane scrollPane = new JScrollPane(noticeTable);
        scrollPane.setBounds(20, 330, 760, 120);
        frame.getContentPane().add(scrollPane);
    }

    private void initDatabase() {

        try {
            connection = connectionPool.getConnection();
            statement = connection.createStatement();
            String createNoticeTable = "CREATE TABLE IF NOT EXISTS announcementboard (id INT(11) NOT NULL AUTO_INCREMENT, title VARCHAR(50) NOT NULL, content TEXT NOT NULL, time DATETIME NOT NULL, PRIMARY KEY (id))";
            statement.executeUpdate(createNoticeTable);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connectionPool.releaseConnection(connection);
            }
        }
    }


    private void loadNoticeData() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = connectionPool.getConnection();
            String sql = "SELECT * FROM announcementboard order by publishTime DESC";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            DefaultTableModel model = (DefaultTableModel) noticeTable.getModel();
            while (resultSet.next()) {
                Object[] row = new Object[4];
                row[0] = resultSet.getInt("id");
                row[1] = resultSet.getString("title");
                row[2] = resultSet.getString("content");
                row[3] = resultSet.getTimestamp("publishTime");
                model.addRow(row);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connectionPool.releaseConnection(connection);

        }
    }


    //添加公告
    private void addNotice() {
        String title = titleField.getText();
        String content = contentArea.getText();
        LocalDateTime localDateTime = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(localDateTime);

        try (Connection connection = connectionPool.getConnection();
             PreparedStatement statement = connection.prepareStatement("INSERT INTO announcementboard (title, content, publishTIme) VALUES (?, ?, ?)")) {

            statement.setString(1, title);
            statement.setString(2, content);
            statement.setTimestamp(3, timestamp);

            int result = statement.executeUpdate();

            if (result == 1) {
                JOptionPane.showMessageDialog(null, "添加公告成功！");
                //更新 表格数据
                //loadNoticeData();
            } else {
                JOptionPane.showMessageDialog(null, "添加公告失败！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "添加公告失败！");
        }
    }

    //删除公告
    private void deleteNotice() {
        int selectedRow = noticeTable.getSelectedRow();

        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(null, "请先选择要删除的公告！");
            return;
        }

        int noticeId = (int) noticeTable.getValueAt(selectedRow, 0);

        int choice = JOptionPane.showConfirmDialog(null, "确定要删除该公告吗？", "确认删除", JOptionPane.YES_NO_OPTION);

        if (choice == JOptionPane.YES_OPTION) {
            try (Connection conn = connectionPool.getConnection();
                 PreparedStatement statement = conn.prepareStatement("DELETE FROM announcementboard WHERE id = ?")) {

                statement.setInt(1, noticeId);
                int result = statement.executeUpdate();

                if (result == 1) {
                    JOptionPane.showMessageDialog(null, "删除公告成功！");
                    loadNoticeData();
                } else {
                    JOptionPane.showMessageDialog(null, "删除公告失败！");
                }

            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "删除公告失败！");
            }
        }
    }

    //更新公告
    private void updateNotice() {
        int selectedRow = noticeTable.getSelectedRow();

        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(null, "请先选择要修改的公告！");
            return;
        }

        int noticeId = (int) noticeTable.getValueAt(selectedRow, 0);
        String title = titleField.getText();
        String content = contentArea.getText();
        LocalDateTime localDateTime = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(localDateTime);


        try (Connection connection = connectionPool.getConnection();
             PreparedStatement statement = connection.prepareStatement("UPDATE announcementboard SET title = ?, content = ?, publishTime = ? WHERE id = ?")) {

            statement.setString(1, title);
            statement.setString(2, content);
            statement.setTimestamp(3, timestamp);
            statement.setInt(4, noticeId);
            int result = statement.executeUpdate();

            if (result == 1) {
                JOptionPane.showMessageDialog(null, "修改公告成功！");
                loadNoticeData();
            } else {
                JOptionPane.showMessageDialog(null, "修改公告失败！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "修改公告失败！\n" + e.getMessage());
        }
    }

    private void searchNotice() {
        String keyword = titleField.getText().trim();
        if (keyword.isEmpty()) {
            loadNoticeData();
            return;
        }

        String sql = "SELECT * FROM announcementboard WHERE id LIKE ? OR title LIKE ?";
        try (Connection connection = connectionPool.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, "%" + keyword + "%");
            statement.setString(2, "%" + keyword + "%");

            ResultSet result = statement.executeQuery();

            List<Announcement> noticeList = new ArrayList<>();
            while (result.next()) {
                int id = result.getInt("id");
                String title = result.getString("title");
                String content = result.getString("content");
                LocalDateTime time = result.getTimestamp("publishTIme").toLocalDateTime();
                Announcement announcement = new Announcement(id, title, content, time);
                noticeList.add(announcement);
            }

            // 将查询结果填充到表格中
            DefaultTableModel model = (DefaultTableModel) noticeTable.getModel();
            model.setRowCount(0);
            for (Announcement announcement : noticeList) {
                Object[] rowData = {announcement.getId(), announcement.getTitle(), announcement.getContent(), announcement.getPublishTime()};
                model.addRow(rowData);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "查询公告失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}

